/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlets;

import domain.Bankaccount;
import domain.Consumption;
import domain.Contract;
import domain.Electricityconsumption;
import domain.Electricitycontract;
import domain.Expense;
import domain.Income;
import domain.Insuranceconsumption;
import domain.Insurancecontract;
import domain.Invoice;
import domain.Mobilecontract;
import domain.Mortgageconsumption;
import domain.Mortgagecontract;
import domain.Salary;
import domain.Userdom;
import domain.Vehiclecar;
import domain.Waterconsumption;
import domain.Watercontract;
import domain.Wcontract;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Date;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import planner.Operations;
import util.Validar;

/**
 *
 * @author Alberto
 */
public class Register extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    private String type = "";

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            type = request.getParameter("type");
            Userdom u = (Userdom) request.getSession().getAttribute("user");

            if (type.equals("note")) {

                String nombre = request.getParameter("nombre");
                String content = request.getParameter("comentario");
                if (Validar.esValidoChar(nombre) && Validar.esValidoChar(content)) {
                    domain.Note n = new domain.Note(u, content, nombre);
                    u.getNotes().add(n);

                    new Operations().addNote(n);
                }
            } else if (type.equals("task")) {
                String nombre = request.getParameter("nombre");
                String comentario = request.getParameter("comentario");
                String date = request.getParameter("fecha");
                if (Validar.esValidoChar(nombre) && Validar.esValidoChar(comentario)) {
                    java.sql.Date fecha = java.sql.Date.valueOf(date);

                    domain.Task t = new domain.Task(u, nombre, fecha, comentario);
                    u.getTasks().add(t);

                    new Operations().addTask(t);
                }
            } else if (type.equals("bankAccount")) {
                String name = request.getParameter("nombre");
                if (Validar.esValidoChar(name)) {
                    Bankaccount b = new Bankaccount(u, name);

                    new Operations().newBankAccount(b);
               }
            } else if (type.equals("income")) {
                String idBank = request.getParameter("bank");
                Integer idB = Integer.parseInt(idBank);
                String concept = request.getParameter("concept");
                String date = request.getParameter("dateIncome");
                String cantidad = request.getParameter("amount");

                if (Validar.esValidoChar(concept) && Validar.esValidoDecimal(cantidad)) {
                    double amount = Double.parseDouble(cantidad);
                    Date dateIncome = java.sql.Date.valueOf(date);
                    Income i = new Income(new Operations().getBankAccount(idB), concept, dateIncome, amount);

                    new Operations().addIncome(i);
                    u.getBankaccount(idB).getIncomes().add(i);

                }

                out.print(Validar.esFecha(date));
            } else if (type.equals("expense")) {
                String idBank = request.getParameter("bank");
                Integer idB = Integer.parseInt(idBank);
                String concept = request.getParameter("concept");
                String date = request.getParameter("dateExpense");
                String cantidad = request.getParameter("amount");

                if (Validar.esValidoChar(concept) && Validar.esValidoDecimal(cantidad)) {

                    double amount = Double.parseDouble(cantidad);
                    Date dateExpense = java.sql.Date.valueOf(date);
                    Expense e = new Expense(new Operations().getBankAccount(idB), concept, dateExpense, amount);

                    new Operations().addExpense(e);
                    u.getBankaccount(idB).getExpenses().add(e);
                }
            } else if (type.equals("user")) {
                String nick = request.getParameter("nick");
                String pass = request.getParameter("pass");
                String name = request.getParameter("name");
                String surname = request.getParameter("surname");
                String date = request.getParameter("date");

                if (Validar.esValidoChar(nick) && Validar.esValidoChar(pass) && Validar.esValidoChar(name) && Validar.esValidoChar(surname)) {

                    Date fecha = java.sql.Date.valueOf(date);
                    Userdom user = new Userdom(nick, pass, name, surname, fecha);

                    new Operations().newUser(user);
                }
            } else if (type.equals("car")) {
                String owner = request.getParameter("titular");
                String mark = request.getParameter("marca");
                String register = request.getParameter("matricula");

                if (Validar.esValidoChar(owner) && Validar.esValidoChar(mark)) {
                    Vehiclecar car = new Vehiclecar(u, mark, register, owner);

                    new Operations().newVehiclecar(car);
                }
            } else if (type.equals("waterCont")) {
                String idBank = request.getParameter("bank");
                Integer idB = Integer.parseInt(idBank);
                String date = request.getParameter("fecha");
                String name = request.getParameter("name");

                if (Validar.esValidoChar(name)) {
                    Date fecha = Date.valueOf(date);

                    Contract c = new Contract(new Operations().getBankAccount(idB), fecha, true, name);
                    Watercontract w = new Watercontract(c, name);

                    new Operations().newWaterContract(w, c);
               }
            } else if (type.equals("wCont")) {
                String idBank = request.getParameter("bank");
                Integer idB = Integer.parseInt(idBank);
                String workName = request.getParameter("workName");
                String salary = request.getParameter("basicSalary");

                if (Validar.esValidoChar(workName) && Validar.esValidoDecimal(salary) && Validar.esValidoNum(idBank)) {

                    Double basicSalary = Double.valueOf(salary);
                    Wcontract wc = new Wcontract(new Operations().getBankAccount(idB), workName, basicSalary);
                    new Operations().newWContract(wc);
                }
            } else if (type.equals("insuranceCont")) {
                String idBank = request.getParameter("bank");
                Integer idB = Integer.parseInt(idBank);
                String coment = request.getParameter("coment");
                String date = request.getParameter("fecha");
                String dateExp = request.getParameter("fechaExp");
                String name = request.getParameter("name");

                if (Validar.esValidoChar(coment) && Validar.esValidoChar(name)) {
                    Date fecha = Date.valueOf(date);
                    Date fechaExp = Date.valueOf(dateExp);
                    Contract c = new Contract(new Operations().getBankAccount(idB), fecha, true, name);
                    Insurancecontract i = new Insurancecontract(c, fechaExp, coment);

                    new Operations().newInsuranceContract(i, c);
                }
            } else if (type.equals("mortgageCont")) {
                String idBank = request.getParameter("bank");
                Integer idB = Integer.parseInt(idBank);
                String date = request.getParameter("fecha");
                String dateExp = request.getParameter("fechaExp");
                String t = request.getParameter("total");
                String i = request.getParameter("interes");
                String name = request.getParameter("name");


                if (Validar.esValidoChar(name) && Validar.esValidoDecimal(i) && Validar.esValidoDecimal(t)) {
                    Date fechaExp = Date.valueOf(dateExp);
                    Date fecha = Date.valueOf(date);
                    double total = Double.valueOf(t);
                    double interes = Double.valueOf(i);
                    Contract c = new Contract(new Operations().getBankAccount(idB), fecha, true, name);
                    Mortgagecontract m = new Mortgagecontract(c, fechaExp, name, total, interes);

                    new Operations().newMortgageContract(m, c);
                }
            } else if (type.equals("mobileCont")) {
                String idBank = request.getParameter("bank");
                Integer idB = Integer.parseInt(idBank);
                String number = request.getParameter("numero");
                Integer numero = Integer.parseInt(number);
                String compania = request.getParameter("compania");
                String date = request.getParameter("fecha");
                String perm = request.getParameter("permanencia");
                if (Validar.esValidoChar(perm) && Validar.esValidoNum(number) && Validar.esValidoChar(compania)) {
                    Date fecha = Date.valueOf(date);

                    Integer pemanencia = Integer.parseInt(perm);
                    Contract c = new Contract(new Operations().getBankAccount(idB), fecha, true, number);
                    Mobilecontract m = new Mobilecontract(c, compania, pemanencia, numero);

                    new Operations().newMobileContract(m, c);
                }
            } else if (type.equals("electricityCont")) {
                String idBank = request.getParameter("bank");
                Integer idB = Integer.parseInt(idBank);
                String compania = request.getParameter("compania");
                String date = request.getParameter("fecha");
                String potencia = request.getParameter("potencia");
                String name = request.getParameter("name");
                if (Validar.esValidoDecimal(potencia) && Validar.esValidoChar(name) && Validar.esValidoChar(compania)) {

                    Date fecha = Date.valueOf(date);
                    Double power = Double.valueOf(potencia);

                    Contract c = new Contract(new Operations().getBankAccount(idB), fecha, true, name);
                    Electricitycontract e = new Electricitycontract(c, compania, power);

                    new Operations().newElectricityContract(e, c);
                }
            } else if (type.equals("electricityConsumption")) {
                Operations o = new Operations();

                String idElecContract = request.getParameter("elecon");
                String amount = request.getParameter("amount");
                String dateFrom = request.getParameter("from");
                String dateTo = request.getParameter("to");

                Integer idE = Integer.parseInt(idElecContract);
                Double cantidad = Double.valueOf(amount);
                Date from = Date.valueOf(dateFrom);
                Date to = Date.valueOf(dateTo);

                if (from.before(to)) {

                    Electricitycontract e = o.getElectricityContract(idE);
                    Contract contract = e.getContract();
                    Bankaccount bank = contract.getBankaccount();

                    if ( Validar.esValidoDecimal(amount)) {

                        Consumption cons = new Consumption(contract, cantidad);

                        Invoice invoice = new Invoice(bank, e.getCompany(), new java.sql.Date((new java.util.Date().getTime())), cantidad);

                        Electricityconsumption eCons = new Electricityconsumption(invoice, cons, from, to);

                        o.newConsumption(cons);
                        o.newInvoice(invoice);
                        o.newElectricityConsumption(eCons);
                    }
                } else {
                }
            } else if (type.equals("salary")) {
                Operations o = new Operations();

                String idWContract = request.getParameter("elecon");
                String amount = request.getParameter("amount");
                String estado = request.getParameter("estado");

                Integer idW = Integer.parseInt(idWContract);
                Double cantidad = Double.valueOf(amount);
                Integer idE = Integer.parseInt(estado);

                Wcontract w = o.getWcontract(idW);

                Salary s = new Salary(w, w.getBankaccount(), "sueldo", new Date(new java.util.Date().getTime()), cantidad, idE);

                o.newSalary(s);



            } else if (type.equals("mortgageConsumption")) {
                Operations o = new Operations();

                String idMortgageContract = request.getParameter("elecon");
                Integer idM = Integer.parseInt(idMortgageContract);


                String amount = request.getParameter("amount");


                String dateFrom = request.getParameter("from");
                String dateTo = request.getParameter("to");
                if (Validar.esValidoDecimal(amount)) {

                    Date to = Date.valueOf(dateTo);
                    Date from = Date.valueOf(dateFrom);
                    Double cantidad = Double.valueOf(amount);
                    if (from.before(to)) {


                        Mortgagecontract m = o.getMortgageContract(idM);
                        Contract contract = m.getContract();
                        out.print(contract.getNameContract());
                        Bankaccount bank = contract.getBankaccount();
                        out.print(bank.getName());

                        Consumption cons = new Consumption(contract, cantidad);

                        Invoice invoice = new Invoice(bank, m.getCompany(), new java.sql.Date((new java.util.Date().getTime())), cantidad);

                        Mortgageconsumption mCons = new Mortgageconsumption(invoice, cons, from, to);

                        o.newConsumption(cons);
                        o.newInvoice(invoice);
                        o.newMortgageConsumption(mCons);

                        u.getBankaccount(bank.getIdBank()).getContract(contract.getIdContract()).getConsumptions().add(cons);

                    } else {
                    }
                }


            } else if (type.equals("insuranceConsumption")) {
                Operations o = new Operations();

                String idInsContract = request.getParameter("elecon");
                Integer idI = Integer.parseInt(idInsContract);
                String dateFrom = request.getParameter("from");
                String amount = request.getParameter("amount");
                String dateTo = request.getParameter("to");

                if (Validar.esValidoDecimal(amount)) {

                    Double cantidad = Double.valueOf(amount);
                    Date from = Date.valueOf(dateFrom);
                    Date to = Date.valueOf(dateTo);
                    if (from.before(to)) {

                        Insurancecontract i = o.getInsuranceContract(idI);
                        Contract contract = i.getContract();
                        Bankaccount bank = contract.getBankaccount();

                        Consumption cons = new Consumption(contract, cantidad);

                        Invoice invoice = new Invoice(bank, i.getCompany(), new java.sql.Date((new java.util.Date().getTime())), cantidad);

                        Insuranceconsumption iCons = new Insuranceconsumption(invoice, cons, from, to);

                        o.newConsumption(cons);
                        o.newInvoice(invoice);
                        o.newInsuranceConsumption(iCons);

                    } else {
                    }
                }

            } else if (type.equals("waterConsumption")) {
                Operations o = new Operations();

                String idElecContract = request.getParameter("elecon");
                Integer idW = Integer.parseInt(idElecContract);
                String dateFrom = request.getParameter("from");
                String amount = request.getParameter("amount");
                String dateTo = request.getParameter("to");

                if (Validar.esValidoDecimal(amount)) {

                    Double cantidad = Double.valueOf(amount);
                    Date from = Date.valueOf(dateFrom);
                    Date to = Date.valueOf(dateTo);

                    if (from.before(to)) {

                        Watercontract w = o.getWaterContract(idW);
                        Contract contract = w.getContract();
                        Bankaccount bank = contract.getBankaccount();

                        Consumption cons = new Consumption(contract, cantidad);

                        Invoice invoice = new Invoice(bank, w.getCompany(), new java.sql.Date((new java.util.Date().getTime())), cantidad);

                        Waterconsumption iCons = new Waterconsumption(invoice, cons, from, to);

                        o.newConsumption(cons);
                        o.newInvoice(invoice);
                        o.newWaterConsumption(iCons);
                    } 

                }
            }
        } finally {
            String url = request.getParameter("redir");

            RequestDispatcher d = request.getRequestDispatcher("./FrontController?redir=" + url);
            d.forward(request, response);
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
